//
//  MCPictureView.swift
//  HXWeibo
//
//  Created by HX on 15/12/3.
//  Copyright © 2015年 HX. All rights reserved.
//

import UIKit

import SDWebImage

/// 微博 配图
class MCPictureView: UICollectionView
{
    // MARK: - 属性 
    /// cell重用标识
    private let ReuseIdentifier = "ReuseIdentifier"
    
    /// 模型
    var status: MCStatus?
        {
            didSet
            {
                //刷新collectionView的内容
                reloadData()
            }
        }
    
    /// 流水布局
    private let flowLayout = UICollectionViewFlowLayout()
    
    required init?(coder aDecoder: NSCoder)
    {
        fatalError("init(coder:) has not been implemented")
    }
    
    init()
    {
        super.init(frame: CGRectZero, collectionViewLayout: flowLayout)
        
        backgroundColor = UIColor.clearColor()
        
        // 注册cell
        self.registerClass(MCPictureViewCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
        
        self.dataSource = self
    }
    /// 计算配图视图的宽高
    func calcViewSize() -> CGSize
    {
        /// 间距
        let margin: CGFloat = 10
        
        //设置itemSize
        let itemSize = CGSize(width: 90, height: 90)
        flowLayout.itemSize = itemSize
        
        // 流水布局的间距
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        
        // 获取图片的数量
        let count = status?.pictureURLs?.count ?? 0
        
        // 根据模型里面的图片数量来计算宽高
        if count == 0
        {
            return CGSizeZero
        }
        if count == 1
        {
            var size = CGSize(width: 150, height: 120)
            
            // 返回图片的大小
            //获取图片的url地址
            let url = status!.pictureURLs![0].absoluteString
            
            // 使用SDWebImage找到这张图片 key: 图片的url地址
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url)
            
            if image != nil
            {
                // 重新设置size
                size = image.size
                print("-----------------------有图片 大小-->\(size)")
            }
            
            if size.width < 40
            {
                size.width = 40
            }
            if size.height < 40
            {
                size.height = 40
            }
            
            flowLayout.itemSize = size
            
            return size
        }
        // 当图片的数量大于1的时候需要设置间距
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 10
        
        if count == 4
        {
            let width = itemSize.width * 2 + margin
            
//            flowLayout.itemSize = CGSize(width: width, height: width)
            
            return CGSize(width: width, height: width)
        }
        // 列数
        let col = 3
        
        // 行数  公式: (count + col - 1) / col 
        //注意：count col 必须是Int类型
        let row = (count + col - 1) / col
        
        // 宽度:列数 * itemSize.width + (col - 1) * margin
        let width = CGFloat(col) * itemSize.width + (CGFloat(col) - 1) * margin
        
        let height = CGFloat(row) * itemSize.width + (CGFloat(row) - 1) * margin
        
        return CGSize(width: width, height: height)
    }
}

// MARK: 扩展
extension MCPictureView: UICollectionViewDataSource
{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return status?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! MCPictureViewCell
        
//        cell.backgroundColor = UIColor.orangeColor()
        
        // 设置cell要显示图片的url
        cell.imageURL = status?.pictureURLs?[indexPath.item]
        
        return cell
    }
}
// xxxxxxxx

// MARK: - 自定义cell
class MCPictureViewCell: UICollectionViewCell
{
    /// 图片的url
    var imageURL: NSURL?
        {
            didSet
            {
                // 使用SDWebImage来加载图片
                bgImageView.sd_setImageWithURL(imageURL)
                
            }
        }
    
    required init?(coder aDecoder: NSCoder)
    {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        
        prepareUI()
    }
    
    private func prepareUI()
    {
        // 添加子控件
        contentView.addSubview(bgImageView)
        
        //添加约束
        bgImageView.ff_Fill(contentView)
    }

    // MARK: - 懒加载
    /// 图片
    private lazy var bgImageView: UIImageView =
    {
        let imageView = UIImageView()
        
        // 设置图片填充模式
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        
        // 超出边界的减掉
        imageView.clipsToBounds = true
        
        return imageView
    }()
    
}































 